package com.example.shiro.filter;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description : 自定义过滤器-验证token
 * @Author : Bruce Lee
 * @CreateTime : 2024/5/28
 */

public class ShiroAuthenticationFilter extends FormAuthenticationFilter {


    /**
     * 直接过滤可以访问的请求类型
     */
    private static final String REQUEST_TYPE = "OPTIONS";

    public ShiroAuthenticationFilter() {
        super();
    }

    /**
     * 判断是否允许访问：false为拦截，true为允许
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) request).getMethod().equals(REQUEST_TYPE)) {
            return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    //  上面的方法返回false后(被拦截)，会进入这个方法；这个方法返回false表示处理完毕(不放行)；返回true表示需要继续处理(放行)
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Content-type", "text/html;charset=UTF-8");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setContentType("application/json");
        res.setStatus(HttpServletResponse.SC_OK);
        res.setCharacterEncoding("UTF-8");
        PrintWriter writer = res.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "未登录");
        writer.write(JSON.toJSONString(map));
        writer.close();
        return false;
    }

}
